const categoryModel = require('../models/categoryModel');
const eventModel = require('../models/eventModel');

// 获取所有分类
async function getAllCategories(req, res, next) {
  try {
    const categories = await categoryModel.getAllCategories();
    res.json(categories);
  } catch (error) {
    next(error);
  }
}

// 获取单个分类
async function getCategoryById(req, res, next) {
  try {
    const { id } = req.params;
    const category = await categoryModel.getCategoryById(id);
    
    if (!category) {
      return res.status(404).json({
        success: false,
        message: '分类不存在'
      });
    }
    
    res.json(category);
  } catch (error) {
    next(error);
  }
}

// 创建分类
async function createCategory(req, res, next) {
  try {
    const categoryData = req.body;
    
    // 基本验证
    if (!categoryData.name) {
      return res.status(400).json({
        success: false,
        message: '缺少必要字段'
      });
    }
    
    // 确保有ID
    if (!categoryData.id) {
      categoryData.id = `category_${Date.now()}`;
    }
    
    // 确保有创建时间
    if (!categoryData.createTime) {
      categoryData.createTime = new Date().toLocaleString();
    }
    
    const newCategory = await categoryModel.createCategory(categoryData);
    
    res.status(201).json(newCategory);
  } catch (error) {
    next(error);
  }
}

// 更新分类
async function updateCategory(req, res, next) {
  try {
    const { id } = req.params;
    const categoryData = req.body;
    
    // 基本验证
    if (!categoryData.name) {
      return res.status(400).json({
        success: false,
        message: '缺少必要字段'
      });
    }
    
    const updatedCategory = await categoryModel.updateCategory(id, categoryData);
    
    if (!updatedCategory) {
      return res.status(404).json({
        success: false,
        message: '分类不存在'
      });
    }
    
    res.json(updatedCategory);
  } catch (error) {
    next(error);
  }
}

// 删除分类
async function deleteCategory(req, res, next) {
  try {
    const { id } = req.params;
    
    // 检查该分类下是否有事件
    const events = await eventModel.getEventsByCategory(id);
    if (events.length > 0) {
      return res.status(400).json({
        success: false,
        message: `无法删除分类，该分类下有 ${events.length} 个事件`
      });
    }
    
    const result = await categoryModel.deleteCategory(id);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '分类不存在'
      });
    }
    
    res.json({
      success: true,
      message: '分类删除成功'
    });
  } catch (error) {
    next(error);
  }
}

module.exports = {
  getAllCategories,
  getCategoryById,
  createCategory,
  updateCategory,
  deleteCategory
}; 